/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.yzg.simple.netty.acyntask.echo;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * 异步处理机制
 */
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当前该EventExecutorGroup 就是彻底异步线程模型去处理耗时业务
     *  线程复用性和 EventLoopGroup 是一样的.
     *
     *  基于handler 添加异步处理机制(推荐)
     */
    static  final EventExecutorGroup group = new DefaultEventExecutorGroup(8);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 我们一般添加比较耗时的操作就会
        // channel 中添加 异步任务,但是执行的线程还是一样的,
        // 虽然异步了,但是该线程任然被阻塞,如果适用于大的业务处理,就有些无力.
        ctx.channel().eventLoop().execute(()->{
            try {
                Thread.sleep(5000);
                System.out.println(" 我是Channel的线程 " +Thread.currentThread().getName());
                ctx.writeAndFlush(Unpooled.copiedBuffer("嘿嘿", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //在异步时间池中添加
        group.submit(()->{
            System.out.println(" EventExecutorGroup 的线程 " +Thread.currentThread().getName());
            ctx.writeAndFlush(Unpooled.copiedBuffer("嘿嘿", CharsetUtil.UTF_8));
        });
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
